package cn.tedu.system.order.service.impl;

import cn.tedu.system.base.exception.ServiceException;
import cn.tedu.system.base.response.JsonResult;
import cn.tedu.system.base.response.StatusCode;
import cn.tedu.system.order.mapper.OrderMapper;
import cn.tedu.system.order.pojo.dto.*;
import cn.tedu.system.order.pojo.entity.Order;
import cn.tedu.system.order.pojo.entity.OrderItem;
import cn.tedu.system.order.pojo.vo.OrderItemVO;
import cn.tedu.system.order.pojo.vo.OrderVO;
import cn.tedu.system.order.service.OrderService;
import cn.tedu.system.user.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    //用户创建订单
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createOrder(OrderCreateRequestDto request, HttpSession session) {
        log.debug("创建订单业务: {}",request);
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null) {
            throw new ServiceException(StatusCode.UNAUTHORIZED);
        }

        // 校验用户权限
        if (!userVO.getId().equals(request.getUserId())) {
            throw new ServiceException(StatusCode.USER_INFORMATION_NOT_MATCH);
        }
        // 校验商品信息
        request.getItems().forEach(item -> {
            if (item.getQuantity() <= 0) {
                throw new ServiceException(StatusCode.PRODUCT_QUANTITY_ABNORMAL);
            }
            if (item.getPrice().doubleValue() <= 0) {
                throw new ServiceException(StatusCode.PRODUCT_PRICE_ABNORMAL);
            }
        });
        // 校验库存前置
        request.getItems().forEach(item -> {
            Integer stock = orderMapper.getStocks(item.getProductId());
            if (stock < item.getQuantity()) {
                throw new ServiceException("商品[" + item.getProductId() + "]库存不足");
            }
        });

        // 1. 生成唯一订单号（示例：时间戳+用户ID+随机数）
        String orderNo = String.format("ORDER_%d_%d_%04d", userVO.getId(), System.currentTimeMillis(), new Random().nextInt(10000));

        // 2. 计算商品总价
        double itemTotal = request.getItems().stream()
                .mapToDouble(item -> item.getPrice().doubleValue() * item.getQuantity())
                .sum();

        // 3. 计算订单总金额（商品总价 + 运费）
        double totalAmount = itemTotal + request.getFreight();

        // 4. 构建订单对象
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserId(request.getUserId());
        order.setMerchantId(request.getMerchantId());
        order.setTotalAmount(totalAmount);
        order.setActualAmount(totalAmount);
        order.setFreight(request.getFreight());
        if (request.getPaymentType()!=null){
            order.setStatus(1);
        }else {
            order.setStatus(0);
        }
        order.setShippingAddress(request.getShippingAddress());
        order.setContactPhone(request.getContactPhone());
        order.setContactName(request.getContactName());
        order.setRemark(request.getRemark());
        order.setPaymentType(request.getPaymentType());
        order.setPaymentTime(new Date());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());

        int m = orderMapper.create(order);
        Long orderId = orderMapper.getOrderId(orderNo);

        if (m > 0) {
            List<OrderItem> orderItems = request.getItems();
            for (OrderItem orderItem : orderItems) {
                orderItem.setOrderId(orderId);
                //获取购买商品id和数量
                Long productId = orderItem.getProductId();
                Integer quantity = orderItem.getQuantity();
                OrderStockParam orderStock = new OrderStockParam();
                orderStock.setProductId(productId);
                orderStock.setQuantity(quantity);
                //查询库存数量
                Integer stock = orderMapper.getStocks(productId);
                if (stock < quantity) {
                    throw new ServiceException(StatusCode.PRODUCT_STOCK_NOT_ENOUGH);
                }
                //修改库存数量
                if(orderMapper.reduceStocks(orderStock)<=0){
                    throw new ServiceException(StatusCode.PRODUCT_STOCK_ABNORMAL);
                }
            }
            //订单商品记录到数据库
            if (orderMapper.addOrderItems(orderItems) <= 0) {
                throw new ServiceException(StatusCode.PRODUCT_STATUS_ERROR);
            }
        }
        /*// 5. 添加订单商品明细
        List<OrderItem> items = request.getItems().stream()
                .map(item -> {
                    OrderItem orderItem = new OrderItem();
                    orderItem.setOrderId(order.getId());
                    orderItem.setProductId(item.getProductId());
                    orderItem.setProductName(item.getProductName());
                    orderItem.setProductImage(item.getProductImage());
                    orderItem.setPrice(item.getPrice());
                    orderItem.setQuantity(item.getQuantity());
                    orderItem.setTotalPrice(item.getPrice().doubleValue()*item.getQuantity());
                    orderItem.setCreateTime(new Date());
                    return orderItem;
                }).collect(Collectors.toList());

        int m=0;
        for (OrderItem orderItem : items) {
            m = orderMapper.addItems(Collections.singletonList(orderItem));
        }

        if (n>0 && m>0) {
            return JsonResult.ok(orderNo);
        }*/
    }

    //直播创建订单
    @Override
    public void createLiveOrder(OrderCreateRequestDto request, HttpSession session) {
        log.debug("直播创建订单业务: {}",request);
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null) {
            throw new ServiceException(StatusCode.UNAUTHORIZED);
        }

        // 校验商品信息
        request.getItems().forEach(item -> {
            if (item.getQuantity() <= 0) {
                throw new ServiceException(StatusCode.PRODUCT_QUANTITY_ABNORMAL);
            }
            if (item.getPrice().doubleValue() <= 0) {
                throw new ServiceException(StatusCode.PRODUCT_PRICE_ABNORMAL);
            }
        });
        // 校验库存前置
        request.getItems().forEach(item -> {
            Integer stock = orderMapper.getLiveStocks(item.getProductId());
            if (stock < item.getQuantity()) {
                throw new ServiceException("商品[" + item.getProductId() + "]库存不足");
            }
        });

        // 1. 生成唯一订单号（示例：时间戳+用户ID+随机数）
        String orderNo = String.format("ORDER_%d_%d_%04d", userVO.getId(), System.currentTimeMillis(), new Random().nextInt(10000));

        // 2. 计算商品总价
        double itemTotal = request.getItems().stream()
                .mapToDouble(item -> item.getPrice().doubleValue() * item.getQuantity())
                .sum();

        // 3. 计算订单总金额（商品总价 + 运费）
        double totalAmount = itemTotal + request.getFreight();

        // 4. 构建订单对象
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserId(request.getUserId());
        order.setMerchantId(request.getMerchantId());
        order.setTotalAmount(totalAmount);
        order.setActualAmount(totalAmount);
        order.setFreight(request.getFreight());
        if (request.getPaymentType()!=null){
            order.setStatus(1);
        }else {
            order.setStatus(0);
        }
        order.setShippingAddress(request.getShippingAddress());
        order.setContactPhone(request.getContactPhone());
        order.setContactName(request.getContactName());
        order.setRemark(request.getRemark());
        order.setPaymentType(request.getPaymentType());
        order.setPaymentTime(new Date());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());

        int m = orderMapper.create(order);
        Long orderId = orderMapper.getOrderId(orderNo);

        if (m > 0) {
            List<OrderItem> orderItems = request.getItems();
            for (OrderItem orderItem : orderItems) {
                orderItem.setOrderId(orderId);
                //获取购买商品id和数量
                Long productId = orderItem.getProductId();
                Integer quantity = orderItem.getQuantity();
                OrderStockParam orderStock = new OrderStockParam();
                orderStock.setProductId(productId);
                orderStock.setQuantity(quantity);
                //查询库存数量
                Integer stock = orderMapper.getLiveStocks(productId);
                if (stock < quantity) {
                    throw new ServiceException(StatusCode.PRODUCT_STOCK_NOT_ENOUGH);
                }
                //修改库存数量
                if(orderMapper.reduceLiveStocks(orderStock)<=0){
                    throw new ServiceException(StatusCode.PRODUCT_STOCK_ABNORMAL);
                }
            }
            //订单商品记录到数据库
            if (orderMapper.addOrderItems(orderItems) <= 0) {
                throw new ServiceException(StatusCode.PRODUCT_STATUS_ERROR);
            }
        }
    }

    //用户修改订单
    @Override
    public void reviseOrder(OrderReviseDto orderReviseDto, HttpSession session) {
        log.debug("用户信息修改业务: {}",orderReviseDto);
        UserVO userVO = (UserVO) session.getAttribute("user");
        if(userVO == null) {
            throw new ServiceException(StatusCode.UNAUTHORIZED);
        }
        if (!userVO.getId().equals(orderReviseDto.getUserId())) {
            throw new ServiceException(StatusCode.USER_INFORMATION_NOT_MATCH);
        }

        Order order = new Order();
        BeanUtils.copyProperties(orderReviseDto,order);
        order.setUpdateTime(new Date());
        order.setPaymentTime(new Date());

        if(orderMapper.reviseOrder(order)<=0){
            throw new ServiceException(StatusCode.FAILED);
        }
    }

    //用户删除订单
    @Override
    public void delete(OrderReviseDto orderReviseDto, HttpSession session) {
        log.debug("删除用户业务:{}",orderReviseDto);
        UserVO userVO = (UserVO) session.getAttribute("user");
        if(userVO == null) {
            throw new ServiceException(StatusCode.UNAUTHORIZED);
        }

        if(orderMapper.deleteOrder(orderReviseDto)<=0){
            throw new ServiceException(StatusCode.FAILED);
        }
    }

    //用户根据状态查询订单
    @Override
    public List<OrderVO> select(Integer status, HttpSession session) {
        log.debug("OrderSelDto:{}",status);
        UserVO userVO = (UserVO) session.getAttribute("user");
        if(userVO == null) {
            throw new ServiceException(StatusCode.UNAUTHORIZED);
        }
        OrderSelDto orderSelDto = new OrderSelDto();
        orderSelDto.setStatus(status);
        orderSelDto.setUserId(userVO.getId());
        List<OrderVO> orderVO = orderMapper.selectOrder(orderSelDto);
        if (orderVO == null && orderVO.size() == 0) {
            throw new ServiceException(StatusCode.FAILED);
        }
        return orderVO;
    }

    //用户查看所有订单
    @Override
    public List<OrderVO> selectAll(HttpSession session) {
        log.debug("查看订单业务参数");
        UserVO userVO = (UserVO) session.getAttribute("user");
        if(userVO == null) {
            throw new ServiceException(StatusCode.UNAUTHORIZED);
        }

        List<OrderVO> orderVO = orderMapper.selectAllOrder(userVO.getId());
        if (orderVO == null && orderVO.size() == 0) {
            throw new ServiceException(StatusCode.FAILED);
        }
        return orderVO;
    }

    //查订单总数
    @Override
    public int selTotal(HttpSession session) {
        UserVO userVO = (UserVO) session.getAttribute("user");
        if(userVO == null) {
            throw new ServiceException(StatusCode.UNAUTHORIZED);
        }
        // 查询总数
        int total = orderMapper.selectOrderCount(userVO.getId());
        return total;
    }

    //查看订单详情
    @Override
    public List<OrderItemVO> selOrderDetail(Long orderId, HttpSession session) {
        log.debug("查看订单详情业务:{}",orderId);
        UserVO userVO = (UserVO) session.getAttribute("user");
        if(userVO == null) {
            throw new ServiceException(StatusCode.UNAUTHORIZED);
        }
        List<OrderItemVO> list = orderMapper.selDetail(orderId);
        return list;
    }

    //商家查询订单
    @Override
    public List<OrderVO> getOrders(Long merchantId, HttpSession session) {
        log.debug("商家查询订单业务:{}",merchantId);
        UserVO userVO = (UserVO) session.getAttribute("user");
        if(userVO == null) {
            throw new ServiceException(StatusCode.UNAUTHORIZED);
        }
        List<OrderVO> orderVOS = orderMapper.getOrders(merchantId);
        log.debug("商家查询订单业务:{}",orderVOS);
        return orderVOS;
    }

    //商家发货功能
    @Override
    public void shipments(OrderStatusParam orderParam, HttpSession session) {
        log.debug("orderNo: {}",orderParam);
        UserVO userVO = (UserVO) session.getAttribute("user");
        if(userVO == null) {
            throw new ServiceException(StatusCode.UNAUTHORIZED);
        }

        Order order = new Order();
        BeanUtils.copyProperties(orderParam,order);
        order.setUpdateTime(new Date());
        if(orderMapper.shipment(order)<=0){
            throw new ServiceException(StatusCode.FAILED);
        }

    }
}

